package org.az.netty_study.p11_netty的黏包与半包;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LoggingHandler;

import java.net.InetSocketAddress;
import java.util.Random;

/**
 * 这种就比较靠谱了，以一个特殊字符作为消息的边界来进行分割，前面介绍过
 * 这个特殊字符一般是'\n'或者'\r\n'
 * 这种方式的一条消息有最大值，因为不可能一直没读到'\n'或者'\r\n',就一直接收下去
 */
public class _5_黏包半包的解决之行解码器 {
    public static void main(String[] args) {
        NioEventLoopGroup group = new NioEventLoopGroup();
        Bootstrap client = new Bootstrap()
                .group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {

                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new LoggingHandler());
                        ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                            @Override
                            public void channelActive(ChannelHandlerContext ctx) throws Exception {
                                //发送10条长短不一的数据
                                Random random = new Random();
                                char c = '0';
                                for (int i = 0; i < 10; i++) {
                                    ByteBuf buf = ctx.alloc().buffer();
                                    //写入一条随机长度，以'\n'结尾的消息
                                    buf.writeBytes(getStr(c, random.nextInt(256) + 1));
                                    ctx.writeAndFlush(buf);
                                    c++;
                                }
                            }
                        });
                    }
                });
        ChannelFuture channelFuture = client.connect(new InetSocketAddress("localhost", 7777));
        channelFuture.channel().closeFuture().addListener(ch -> {
            group.shutdownGracefully();
        });
    }

    static byte[] getStr(char c, int len) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < len; i++) {
            sb.append(c);
        }
        sb.append('\n');
        return sb.toString().getBytes();
    }
}
